﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Data;

using System.Runtime.InteropServices;
using System.Web;

using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;

namespace DotNetNuke.Modules.UserDefinedTable
{


  public class DataTypeURL : DataType
  {



    [StructLayout(LayoutKind.Sequential)]
    private struct FieldSetting
    {
      public string Title;
      public string outputFormat;
      public bool abbreviate;
    }



    private void FillHiddenColumns(int ModuleId, DotNetNuke.Modules.UserDefinedTable.TokenReplace objTokenReplace, PortalSettings PortalSettings, Hashtable settings, bool bolNewWindowSetting, FileController fc, TabController TabCtrl, DataRow row, FieldSetting field)
    {
      bool flag;
      string fileName;
      string str2 = string.Empty;
      string strURL = (string)row[field.Title];

      if (bolNewWindowSetting)
        flag = URLUtil.OpenUrlInNewWindow(ref strURL);
      
      else
      {
        switch (DotNetNuke.Common.Globals.GetURLType(URLUtil.StripURL(ref strURL)))
        {
          case TabType.File:
            flag = true;
            break;

          case TabType.Tab:
            flag = false;
            break;

          default:
            flag = !strURL.StartsWith(DotNetNuke.Common.Globals.ApplicationMapPath, StringComparison.OrdinalIgnoreCase);
            break;
        }
      }

      fileName = field.outputFormat;
      if (!string.IsNullOrEmpty(fileName))
        fileName = objTokenReplace.ReplaceEnvironmentTokens(fileName, row);
      
      bool flag2 = true;
      string s = "";
      strURL = URLUtil.StripURL(ref strURL);

      if ( string.IsNullOrEmpty(strURL) )
        return;
      
      switch (DotNetNuke.Common.Globals.GetURLType(strURL))
      {
        case TabType.File:
          if ( string.IsNullOrEmpty(fileName) )
          {
            if (!strURL.ToLowerInvariant().StartsWith("fileid="))
            {
              if (field.abbreviate & (strURL.IndexOf("/") > -1))
                fileName = strURL.Substring(strURL.LastIndexOf("/") + 1);
              
              else
                fileName = strURL;
              
            }
            else
            {
              FileInfo fileById = fc.GetFileById(int.Parse(strURL.Substring(7)), PortalSettings.PortalId);

              if (fileById != null)
              {
                if (field.abbreviate)
                  fileName = fileById.FileName;
                
                else
                  fileName = fileById.Folder + fileById.FileName;
                
              }
            }
          }
          s = DotNetNuke.Common.Globals.LinkClick(strURL, PortalSettings.ActiveTab.TabID, ModuleId);
          break;

        case TabType.Normal:
        case TabType.Url:
          if ( string.IsNullOrEmpty(fileName) )
          {
            if (!(field.abbreviate & (strURL.IndexOf("/") > -1)))
              fileName = strURL;
            
            else
              fileName = strURL.Substring(strURL.LastIndexOf("/") + 1);
            
          }
          if (!Utilities.CBoolN((settings[SettingName.URLDownloadTracking]), false))
            s = strURL;
          
          break;

        case TabType.Tab:
          {
            DotNetNuke.Entities.Tabs.TabInfo info = TabCtrl.GetTab(int.Parse(strURL), PortalSettings.PortalId, false);
            if (info == null)
            {
              fileName = DotNetNuke.Services.Localization.Localization.GetString("PageNotFound.ErrorMessage", DotNetNuke.Common.Globals.ResolveUrl(string.Format("~{0}{1}/SharedResources.resx", Definition.PathOfModule, DotNetNuke.Services.Localization.Localization.LocalResourceDirectory)));
              s = string.Empty;
              flag2 = false;
              break;
            }
            if ( string.IsNullOrEmpty(fileName) )
            {
              if (field.abbreviate)
              {
                fileName = info.TabName;
                break;
              }

              string str5 = string.Empty;
              string tabName;
              TabInfo info3;

              if ((info.BreadCrumbs != null) && (info.BreadCrumbs.Count > 0))
              {
                foreach (TabInfo b in info.BreadCrumbs)
                {
                  info3 = b;
                  tabName = info3.TabName;

                  if ( !string.IsNullOrEmpty(str5) )
                    str5 = str5 + string.Format("<img src=\"{0}/images/breadcrumb.gif\" border=\"0\" alt=\"Spacer\"/>", DotNetNuke.Common.Globals.ApplicationPath);

                  str5 = str5 + tabName;
                }
              }
              fileName = info.TabPath.Replace("//", string.Format("<img src=\"{0}/images/breadcrumb.gif\" border=\"0\" alt=\"Spacer\"/>", DotNetNuke.Common.Globals.ApplicationPath));
            }

            if (Utilities.CBoolN((settings[SettingName.URLDownloadTracking]), false))
              s = DotNetNuke.Common.Globals.LinkClick(strURL, PortalSettings.ActiveTab.TabID, ModuleId);

            else
              s = DotNetNuke.Common.Globals.NavigateURL(int.Parse(strURL));

            break;
          }
        //default:
        //  break;
      }

      if (Utilities.CBoolN((settings[SettingName.ForceDownload]), false))
        s = s + "&amp;forcedownload=true";
      
      if (flag2)
        str2 = string.Format("<!--{1}--><a href=\"{0}\"{2}>{1}</a>", HttpUtility.HtmlEncode(s), fileName, flag ? " target=\"_blank\"" : "").ToString();
      
      else
        str2 = fileName;
      
      row[field.Title] = str2;
      row[field.Title + DataTableColumn.Appendix_Caption] = fileName;
      row[field.Title + DataTableColumn.Appendix_Original] = strURL;
      row[field.Title + DataTableColumn.Appendix_Url] = s;
    }





    private void PrepareHiddenColumns(DataSet ds, ArrayList fields, DataTable tableData)
    {
      IEnumerator enumerator = null;
      try
      {
        enumerator = ds.Tables[DataSetTableName.Fields].Rows.GetEnumerator();
        while (enumerator.MoveNext())
        {
          DataRow current = (DataRow)enumerator.Current;
          if ((string)current[FieldsTableColumn.Type] == this.Name)
          {
            FieldSetting setting2 = new FieldSetting();
            FieldSetting setting3 = setting2;
            setting3.Title = (string)current[FieldsTableColumn.Title];
            setting3.outputFormat = Utilities.CStrN((current[FieldsTableColumn.OutputSettings]), "");
            setting3.abbreviate = Utilities.CBoolN((current[FieldsTableColumn.NormalizeFlag]), false);
            FieldSetting setting = setting3;
            fields.Add(setting);
            tableData.Columns.Add(new DataColumn(setting.Title + DataTableColumn.Appendix_Url, typeof(string)));
            tableData.Columns.Add(new DataColumn(setting.Title + DataTableColumn.Appendix_Caption, typeof(string)));
            tableData.Columns.Add(new DataColumn(setting.Title + DataTableColumn.Appendix_Original, typeof(string)));
          }
        }
      }
      finally
      {
        if (enumerator is IDisposable)
        {
          (enumerator as IDisposable).Dispose();
        }
      }
    }




    public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int ModuleId, bool noScript)
    {
      if (ds != null)
      {
        ArrayList fields = new ArrayList();
        DataTable tableData = ds.Tables[DataSetTableName.Data];
        DotNetNuke.Modules.UserDefinedTable.TokenReplace replace2 = new DotNetNuke.Modules.UserDefinedTable.TokenReplace();
        replace2.ModuleId = ModuleId;
        DotNetNuke.Modules.UserDefinedTable.TokenReplace objTokenReplace = replace2;
        this.PrepareHiddenColumns(ds, fields, tableData);

        if (fields.Count > 0)
        {
          IEnumerator enumerator = null;
          PortalSettings currentPortalSettings = PortalController.GetCurrentPortalSettings();
          Hashtable moduleSettings = new ModuleController().GetModuleSettings(ModuleId);
          bool bolNewWindowSetting = Utilities.CBoolN((moduleSettings[SettingName.URLNewWindow]), false);
          FileController fc = new FileController();
          TabController tabCtrl = new TabController();
          try
          {
            enumerator = tableData.Rows.GetEnumerator();
            while (enumerator.MoveNext())
            {
              IEnumerator enumerator2 = null;
              DataRow current = (DataRow)enumerator.Current;
              try
              {
                enumerator2 = fields.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                  FieldSetting field = (FieldSetting)enumerator2.Current;
                  this.FillHiddenColumns(ModuleId, objTokenReplace, currentPortalSettings, moduleSettings, bolNewWindowSetting, fc, tabCtrl, current, field);
                }
                continue;
              }
              finally
              {
                if (enumerator2 is IDisposable)
                  (enumerator2 as IDisposable).Dispose();

              }
            }
          }
          finally
          {
            if (enumerator is IDisposable)
              (enumerator as IDisposable).Dispose();

          }
        }
      }
    }





    public override string Name
    {
      get
      {
        return "URL";
      }
    }





    public override string SupportedCasts
    {
      get
      {
        return string.Format("{0}|Image", base.SupportedCasts);
      }
    }





    public override bool SupportsDefaultValue
    {
      get
      {
        return true;
      }
    }





    public override bool SupportsEditing
    {
      get
      {
        return true;
      }
    }





    public override bool SupportsInputSettings
    {
      get
      {
        return true;
      }
    }





    public override bool SupportsNormalizeFlag
    {
      get
      {
        return true;
      }
    }





    public override bool SupportsOutputSettings
    {
      get
      {
        return true;
      }
    }




    public override bool SupportsSearch
    {
      get
      {
        return true;
      }
    }




  }

}

